<?php

namespace app\admin\controller\promotion;

use app\admin\service\PromotionTableService;
use ShidianUtil\Thinkphp\Response\ApiResponse;
use ShidianUtil\Utils\TimeUtil;
use think\APP;
use think\exception\ValidateException;
use think\Request as Request;

/**
 * 渠道数据统计
 * Class PromotionTable
 * @package app\admin\controller\promotion
 */
class PromotionTable
{
    // 请求参数
    private Request $request;
    private PromotionTableService $service;

    public function __construct(Request $request, PromotionTableService $service)
    {
        $this->request = $request;
        $this->service = $service;
    }

    /**
     * @return ApiResponse
     * @url /promotion/promotion_table/index
     */
    public function index()
    {
        $request = $this->request;

        // $defaultChains = ['h5-landing1-A', 'h5-landing1-B', 'h5-lawsuit-A', 'h5-lawsuit-B'];
        $defaultChains = [];

        $chain = $request->param('chain', null);

        if (!is_null($chain)) {
            $defaultChains = [$chain];
        }

        $chains = $request->param('chains', $defaultChains);

        $promotionGroupIds = $request->param('promotionGroupIds', [1]);
        $groupId = $promotionGroupIds[0] ?? null;

        $defaultStartTime = TimeUtil::stamp(TimeUtil::MONTH, time());
        $defaultEndTime = TimeUtil::stamp(TimeUtil::MONTH, $defaultStartTime, false);

        $startTime = $request->param('startTime', $defaultStartTime);
        $endTime = $request->param('endTime', $defaultEndTime);

        if (!is_numeric($startTime)) {
            throw new ValidateException('请选择开始时间');
        }
        if (!is_numeric($endTime)) {
            throw new ValidateException('请选择结束时间');
        }

        $startTime = TimeUtil::stamp(TimeUtil::DAY, $startTime);
        $endTime = TimeUtil::stamp(TimeUtil::DAY, $endTime, false);


        return ApiResponse::success($this->service->index($groupId, $chains, $startTime, $endTime));
    }
}
